package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 1.分页+模糊查询
     *
     * @param pageBean
     * @return
     */
    @Override
    public PageResult queryPage(QueryPageBean pageBean) {
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
        Page<Menu> page = menuMapper.queryPage(pageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 2.获取所有的父级菜单id
     *
     * @return
     */
    @Override
    public List<Menu> getParentMenuIds() {
        return menuMapper.getParentMenuIds();
    }

    /**
     * 3.创建菜单
     *
     * @param menu
     */
    @Override
    public void addMenu(Menu menu) {
        if (menu.getParentMenuId() == null)
            menu.setLevel(1);
        else
            menu.setLevel(2);
        menuMapper.addMenu(menu);
    }

    /**
     * 4.查询菜单数据
     *
     * @param id
     * @return
     */
    @Override
    public Menu getMenuById(Integer id) {
        return menuMapper.getMenuById(id);
    }

    /**
     * 5.更新菜单数据
     *
     * @param menu
     */
    @Override
    public void updateMenu(Menu menu) {
        menuMapper.updateMenu(menu);
    }

    /**
     * 6.删除菜单数据
     *
     * @param id
     */
    @Override
    public Result deleteMenuById(Integer id) {

        Menu dbMenu = menuMapper.getMenuById(id);
        if (dbMenu.getChildren().size() > 0) {
            return new Result(false,
                    MessageConstant.DELETE_MENU_FAIL + ",当前删除的菜单有菜单,不能删除");
        }

        // 执行删除操作
        menuMapper.deleteMenuById(id);
        return new Result(true, MessageConstant.DELETE_MENU_SUCCESS);
    }


}
